import socket
import threading

connected = False


def t_recv_main(client_socket):
    global connected
    # 接收消息
    while True:
        try:
            recv_bytes = client_socket.recv(1024)
            if len(recv_bytes) == 0:
                connected = False
                break
            recv_msg = recv_bytes.decode("gbk")
            print(f"收到消息{recv_msg}")
        except ConnectionAbortedError as e:
            print(f"停止接收消息")
            # break
        except OSError as e:
            print(f"停止接收消息 ,连接关闭")
            break


def main():
    # 构建客户端套接字实例
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        global connected
        # 连接服务器
        SERVER_ADDRESS = ("192.168.11.151", 60000)
        client_socket.connect(SERVER_ADDRESS)
        connected = True
    except ConnectionRefusedError as e:
        print("连接出异常",e)

    else:
        t_recv = threading.Thread(target=t_recv_main, args=(client_socket, ))
        t_recv.start()

        # 发送消息
        while True:
            send_msg = input("输入发送的内容")
            if send_msg == "exit":
                client_socket.close()
                break
            else:
                if connected:
                    send_bytes = send_msg.encode("gbk")
                    client_socket.send(send_bytes)
                    print("发送成功")
                else:
                    print(f"已断开 不能发送消息")
                    break




if __name__ == '__main__':
    main()
